package com.cdm.persistence;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import net.sf.frails.JSFHelper;
import net.sf.frails.bean.annotations.DefConverter;

import com.cdm.domain.dao.UserDAO;
import com.cdm.domain.service.Service;
import com.cdm.domain.service.ServiceImpl;

@DefConverter(id = "contentTypeConverter", targetClass = ContentType.class)
public class ContentTypeConverter implements Converter {

	public Object getAsObject(FacesContext facesContext, UIComponent arg1, String string) {
		if (null == string || string.length() == 0) {
			return null;
		}
		Long id = 0l;
		try {
			id = new Long(string);
		} catch (NumberFormatException e) {
			JSFHelper.addMessage("Input must be a number.");
			e.printStackTrace();
		}
		ContentType contentType = EntityManagerHelper.getEntityManager().find(ContentType.class, id);
		return contentType;
	}

	public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object) {
		String result = null;

		if (object != null) {
			if (object instanceof ContentType) {
				ContentType contentType = (ContentType) object;
				result = contentType.getId().toString();
			}
		} else {
			throw new IllegalArgumentException("object:" + object + " of type:" + object.getClass().getName()
			        + "; expected type: ContentType");
		}

		return result;

	}

}
